<%--
  -	Date: 2012-07-30
  -
  - Copyright (C) 2012 Jawa Software. All rights reserved.
  - 
  - 增加试题页面。
--%>
<%@page language="java" pageEncoding="utf-8"%>
<%@page import="org.jawa.core.database.DbConnectionManager,org.jawa.jdbc.*"%>
<%@page import="java.sql.Connection"%>
<%@page import="org.jawa.core.database.SequenceManager"%>
<%@page import="org.jawa.core.log.Log"%>
<%@page import="org.jawa.exam.question.QuestionManager"%>
<%@page import="org.jawa.admin.util.ParamUtils,org.jawa.core.util.*,org.jawa.core.JawaServer,org.jawa.exam.model.Question,org.jawa.exam.model.QuestionOption"%>
<%@page import="java.util.*,java.net.*,org.apache.commons.lang.StringUtils"%>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<jsp:useBean id="webManager" class="org.jawa.admin.util.WebManager"  />
<%
	webManager.init(request, response, session, application, out);
	String path = request.getContextPath();
%>

<%
	Map<String, String> errors = new HashMap<String, String>();
	boolean success;

	boolean another = request.getParameter("save-next") != null;
	boolean create = another || request.getParameter("save") != null;
	boolean edit = request.getParameter("edit") != null;

	Long questionId = ParamUtils.getLongParameter(request,"id",-1L);
	Question question  = null;
	if(edit){
		try{
		    question = QuestionManager.getInstance().getQuestion(questionId);
		}catch(Exception ex){
			//忽略
		}
	}
	if(null==question){
	    question = new Question();
	}
	
	String questionType = ParamUtils.getParameter(request, "questionType");
	if (create) {
		
        if (errors.size() == 0) {
            try{
	            question = new Question();
	            ParamUtils.populateBean(question, request);
	    		Long nextQuestionId = SequenceManager.nextID(JawaConstants.DB_QUESTION_SEQ);
	    		question.setQuestionId(nextQuestionId);
	    		
	    		String[] answerSelect = ParamUtils.getParameters(request,"answerSelect");
	    		//单选 和 多选 需要增加试题选项
	    		List questionOptions = new ArrayList();
		        if("1".equals(questionType) || "2".equals(questionType)){
		        	String[] optionContents = ParamUtils.getParameters(request, "optionContent");
		        	String[] optionCodes = ParamUtils.getParameters(request, "optionCode");
		        	int i =0;
		        	for(String optionContent:optionContents){
		        	    Long nextQuestionOptionId =SequenceManager.nextID(JawaConstants.DB_QUESTIONOPTION_SEQ);
		        		QuestionOption questionOption = new QuestionOption();
		        		questionOption.setQuestionId(nextQuestionId);
		        		questionOption.setOptionContent(optionContent);
		        		questionOption.setOpationCode(optionCodes[i++]);
		        		questionOption.setOptionId(nextQuestionOptionId);
		        		questionOptions.add(questionOption);
		        	}
		       }
		          
		        question.setQuestionAnswer(StringUtils.join(answerSelect, "|"));   
	            question = QuestionManager.getInstance().createQuestion(question,questionOptions);
	            success = true;
	            if (another) {
		          response.sendRedirect("question-form.jsp?create=true&success=true");
	            }
	            else {
		          response.sendRedirect("index.jsp?create=true&success=true");
	            }
	            return;
            }catch(Exception ex){
        	    success = false;
        	 	errors.put("general","");
        		//记录审记信息
        		Log.error("创建试题时发生错误!",ex);
            }
        }
        else {
            response.sendRedirect("index.jsp");
        }
	}
%>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>创建试题</title>
		<meta name="pageID" content="2101" />
		<script src="<%= path %>/kindeditor/kindeditor.js"></script>
	</head>
	<body>
	
	<div class="row-fluid">

		<ul class="breadcrumb">
			<li>您现在的位置:</li>
			<li><a href="<%=path%>/admin/index.jsp">考试管理</a></li>
			<li><span class="divider">/</span></li>
			<li class="active">创建试题</li>
		</ul>

		<div class="page-header hide">
			<h3>创建试题</h3>
		</div>
		<%
				if(errors.get("general")!=null)
				{
		%>		
				  <div class="alert alert-error fade in">
				    <a class="close" data-dismiss="alert" href="#">×</a>
					<strong>创建试题时发生错误.</strong>
				  </div>			
		<%	
				}
		%>		
		<%
			if("true".equals(request.getParameter("create")) && "true".equals(request.getParameter("success"))) 
			{
		%>
			<p class="alert alert-success">
				<a class="close" data-dismiss="alert" href="#">×</a> 
					 创建试题成功!
				</p>
		<%  
			} 
		%>
		<form action="question-form.jsp" method="post" class="form-horizontal well">
			<fieldset>
				<legend>创建试题 </legend>
				<div class="control-group">
					<label class="control-label"> 试题类型: </label>
					<div class="controls">
						<select id="questionType" name="questionType" class="select input-xxlarge" onclick="questionTypeChange();">
							<option value="">请选择</option>
							<option value="1" <%=StringUtils.equals(question.getQuestionType(),"1")?"selected=\"selected\"":"" %>>单选题</option>
							<option value="2" <%=StringUtils.equals(question.getQuestionType(),"2")?"selected=\"selected\"":"" %>>多选题</option>
							<option value="3" <%=StringUtils.equals(question.getQuestionType(),"3")?"selected=\"selected\"":"" %>>判断题</option>
							<option value="4" <%=StringUtils.equals(question.getQuestionType(),"4")?"selected=\"selected\"":"" %>>问答题</option>
						</select>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label"> 试题内容: </label>
					<div class="controls">
						<textarea name="questionContent" rows="3" cols="50" class="input-xxlarge"><%=StringUtils.trimToEmpty(question.getQuestionContent()) %></textarea>
					</div>
				</div>
				<div id="questionOptionsDiv" class="control-group" style="display:<%=edit?"":"none"%>">
					<label class="control-label"> 试题选项: </label>
					<div class="controls">
						<div class="row-fluid">
							<table id="optionContentTable" >
							    <thead>
							     <tr>
							      <td>
									  <button type="button" class="btn btn-info addRow" > <i class="icon-plus icon-white"></i> 增加选项</button>
							      </td>
							     </tr>
							    </thead>
								<tbody>
									<%
									 	if(edit){
									 	    List<QuestionOption> questionOptions = QuestionManager.getInstance().getQuestionOptions(question.getQuestionId());
									 	    if("1".equals(question.getQuestionType()) || "2".equals(question.getQuestionType()))
									 	    {
										 	    for(Iterator<QuestionOption> iter =questionOptions.iterator();iter.hasNext(); ){
										 			QuestionOption questionOption = iter.next();
													%>
													<tr>
														<td>
														     <label class="input-prepend input-append row-fluid " style="margin-bottom: .5em;"> <span class="add-on"><%=questionOption.getOpationCode() %>:</span>
																<input type="hidden" name="optionCode" value="<%=questionOption.getOpationCode() %>">
																<input type="text" name="optionContent" class="input-xxlarge" value="<%=questionOption.getOptionContent()%>">
														     	<span class="add-on delRow"><i class="icon-minus icon-white"></i></span>
														     </label>
														</td>
													</tr>
													<%									 			
										 	    }
									 	    }
									%>
									
									<%     
									 	}else{
									 	//增加
									%>
										<tr>
											<td>
											     <label class="input-prepend input-append row-fluid " style="margin-bottom: .5em;"> <span class="add-on">A:</span>
													<input type="hidden" name="optionCode" value="A">
													<input type="text" name="optionContent" class="input-xxlarge">
											     	<span class="add-on delRow"><i class="icon-minus icon-white"></i></span>
											     </label>
											</td>
										</tr>
										<tr>
											<td>
											     <label class="input-prepend input-append row-fluid " style="margin-bottom: .5em;"> <span class="add-on">B:</span>
													<input type="hidden" name="optionCode" value="B">
													<input type="text" name="optionContent" class="input-xxlarge">
												    <span class="add-on delRow"><i class="icon-minus icon-white"></i></span>
											     </label>
											</td>
										</tr>
										<tr>
											<td>
											     <label class="input-prepend input-append row-fluid " style="margin-bottom: .5em;"> <span class="add-on">C:</span>
													<input type="hidden" name="optionCode" value="C">
													<input type="text" name="optionContent" class="input-xxlarge">
											        <span class="add-on delRow"><i class="icon-minus icon-white"></i></span>
											     </label>
											</td>
										</tr>
										<tr>
											<td>
											    <label class="input-prepend input-append row-fluid " style="margin-bottom: .5em;"> <span class="add-on">D:</span>
													<input type="hidden" name="optionCode" value="D">
													<input type="text" name="optionContent" class="input-xxlarge">
												    <span class="add-on delRow"><i class="icon-minus icon-white"></i></span>
											    </label>
											</td>
										</tr>
									<%     
									 	}
									%>
								</tbody>
							</table>
						</div>
					</div>
				</div>
				<div id="questionAnswerDiv" class="control-group"  style="display:<%=edit?"":"none"%>">
					<label class="control-label"> 试题答案: </label>
					<div class="controls">
							<%	
							    String editSelect = ""; 
								if(edit){
							 	    List<QuestionOption> questionOptions = QuestionManager.getInstance().getQuestionOptions(question.getQuestionId());
							 	    if("1".equals(question.getQuestionType()) || "2".equals(question.getQuestionType()))
							 	    {
								 	    for(Iterator<QuestionOption> iter =questionOptions.iterator();iter.hasNext(); ){
								 			QuestionOption questionOption = iter.next();
								 			
								 			String checked = "  "; 
								 			if(question.getQuestionAnswer().indexOf(questionOption.getOpationCode())>0){
								 			   checked = "checked=\"checked\" "; 
								 			}
								 			
								 			if("1".equals(question.getQuestionType())){
								 			   editSelect +=("<label class=\"radio inline   \"><input type=\"radio\" "+checked+" name=\"answerSelect\" value=\""+questionOption.getOpationCode()+"\"><span class=\"add-on\">"+questionOption.getOpationCode()+"</span></label>");
								 			}
								 			if("2".equals(question.getQuestionType())){
								 			   editSelect +=("<label class=\"checkbox inline   \"><input type=\"checkbox\" "+checked+" name=\"answerSelect\" value=\""+questionOption.getOpationCode()+"\"><span class=\"add-on\">"+questionOption.getOpationCode()+"</span></label>");
								 			}
											%>
											
											<%									 			
								 	    }
							 	    }
							 	    
								}
							%>
					    <div id="radioSelectAnswer" style="display: <%=(edit && "1".equals(question.getQuestionType()))?"":"none"%>">
					        <%="1".equals(question.getQuestionType())?editSelect:"" %>
					    </div>
					    <div id="checkboxSelectAnswer" style="display: <%=(edit && "2".equals(question.getQuestionType())) ?"":"none"%>">
							<%="2".equals(question.getQuestionType())?editSelect:"" %>
					    </div>
					    <div id="decideSelectAnswer" style="display: <%=(edit&& "3".equals(question.getQuestionType()))?"":"none"%>">
						    <label class="checkbox inline  ">
				                 <input type="radio" name="answerSelect" value="true" <%=question.getQuestionAnswer().equals("true")?"checked=\"checked\"":"" %> ><span class="add-on">正确</span>
				            </label>
						    <label class="checkbox inline  ">
				                 <input type="radio" name="answerSelect" value="false" <%=question.getQuestionAnswer().equals("true")?"checked=\"false\"":"" %>><span class="add-on">错误</span>
				            </label>
					    </div>
						<input  type="hidden" name="questionAnswer">					
					</div>
				</div>
				<div class="control-group">
					<label class="control-label"> 试题难度: </label>
					<div class="controls">
						<select name="difficulty" class="select " >
							<option value="" >请选择</option>
							<option value="1"  <%=StringUtils.equals(question.getDifficulty(),"1")?"selected=\"selected\"":"" %>>容易</option>
							<option value="2"  <%=StringUtils.equals(question.getDifficulty(),"2")?"selected=\"selected\"":"" %>>难</option>
							<option value="3"  <%=StringUtils.equals(question.getDifficulty(),"3")?"selected=\"selected\"":"" %>>困难</option>
						</select>
					</div>
				</div>				
				<div class="control-group">
					<label class="control-label"> 试题分值: </label>
					<div class="controls">
					    <div class="input-prepend input-append">
							<input name="questionScore" type="text" maxlength="2" value="<%=question.getQuestionScore() == null?0:question.getQuestionScore()%>">
							<span class="add-on">分</span>
					    </div>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label"> 答题限时: </label>
					<div class="controls">
					    <div class="input-prepend input-append">
							<input name="timeOut" type="text" maxlength="3" value="<%= question.getTimeOut()==null?0:question.getTimeOut() %>">
							<span class="add-on">秒</span>
					    </div>
					</div>
				</div>
				<div class="control-group">
					<label class="control-label"> 解题思路: </label>
					<div class="controls">
						<textarea name="questionDesc" rows="3" cols="50" class="input-xxlarge"><%=StringUtils.trimToEmpty(question.getQuestionDesc())%> </textarea>
					</div>
				</div>
				<div class="form-actions">
					<input type="submit" name="save" value="保存" class="btn btn-primary">
					<input type="submit" name="save-next" value="保存并继续" class="btn btn-primary">
					<input type="button" name="return" value="返回" class="btn" onclick="window.location.href='index.jsp'" />
				</div>
			</fieldset>
		</form>

	</div>

	<script src="<%=path%>/scripts/bootstrap.js"></script>
	<script src="<%=path%>/scripts/jquery.table.addrow.js"></script>
	<script src="<%=path%>/scripts/jquery.tmpl.js"></script>
		<script>
			var contentEditor;
			var descEditor;
			$().ready(function() {
				$("#optionContentTable").tableAutoAddRow({autoAddRow:false});
				$(".delRow").btnDelRow(function(row){
					ajustOptionCodeTxt(row);
				});
				$(".addRow").btnAddRow(function(row){
					alert('addRow');
					ajustOptionCodeTxt(row);
				});
			});
			KindEditor.ready(function(K) {
				contentEditor = K.create('textarea[name="questionContent"]', {
					resizeType : 1,
					allowPreviewEmoticons : false,
					allowImageUpload : false,
					items : [
						'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
						'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
						'insertunorderedlist', '|', 'emoticons', 'image', 'link']
				});
				descEditor = K.create('textarea[name="questionDesc"]', {
					resizeType : 1,
					allowPreviewEmoticons : false,
					allowImageUpload : false,
					items : [
						'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
						'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
						'insertunorderedlist', '|', 'emoticons', 'image', 'link']
				});
			});
			
			/**
			* 试题类型选择事件
			*/
			function questionTypeChange(){
				$('#questionOptionsDiv').hide();
				$('#questionAnswerDiv').hide();
				$('#radioSelectAnswer').hide();
				$('#checkboxSelectAnswer').hide();
				$('#decideSelectAnswer').hide();
				
				var questionType = $('#questionType').val();
				if("1"==questionType){
					$('#questionOptionsDiv').show();
					$('#questionAnswerDiv').show();
					$('#radioSelectAnswer').show();
				}
				if("2"==questionType){
					$('#questionOptionsDiv').show();
					$('#questionAnswerDiv').show();
					$('#checkboxSelectAnswer').show();
				}
				if("3"==questionType){
					$('#questionAnswerDiv').show();
					$('#decideSelectAnswer').show();
				}
				if("4"==questionType){
					
				}
				
				ajustOptionCodeTxt();
			}
			
			/**
			* 根据试题类型与选项调整答案显示区域
			*/
			function ajustOptionCodeTxt(){
				var questionType = $('#questionType').val();
				var charStr = 65;
				$('#radioSelectAnswer').empty();				
				$('#checkboxSelectAnswer').empty();				
				$("#optionContentTable span[class='add-on']").each(function(){
					 $(this).html(String.fromCharCode(charStr)+":");
					 $(this).parent().find("input[name='optionCode']").val(String.fromCharCode(charStr));
					 if("1"==questionType){
						$('#radioSelectAnswer').append("<label class=\"radio inline   \"><input type=\"radio\" name=\"answerSelect\" value=\""+String.fromCharCode(charStr)+"\"><span class=\"add-on\">"+String.fromCharCode(charStr)+"</span></label>");
					 }
					 if("2"==questionType){
						 $('#checkboxSelectAnswer').append("<label class=\"checkbox inline  \"><input type=\"checkbox\" name=\"answerSelect\" value=\""+String.fromCharCode(charStr)+"\"><span class=\"add-on\">"+String.fromCharCode(charStr)+"</span></label>");	
					 }
					 if("3"==questionType){
						$('#questionAnswerDiv').show();
						$('#decideSelectAnswer').show();
					 }
						
					 charStr ++;
				});
			}
			
			function validateForm(){
				return true;
			}
		</script>
		
	</body>